/*
 * Copyright 2009 SHOP.COM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shop.opensocial.mediated.shindig.request;

import com.google.inject.Inject;
import com.shop.opensocial.mediated.config.MediatedDriverFactory;
import com.shop.opensocial.mediated.shindig.factories.GadgetContextMediatorFactory;
import com.shop.opensocial.mediated.types.GadgetContextMediator;
import com.shop.opensocial.mediated.services.GadgetContextHandlerMediator;
import org.apache.shindig.common.servlet.InjectedServlet;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.render.Renderer;
import org.apache.shindig.gadgets.render.RenderingResults;
import org.apache.shindig.gadgets.servlet.HttpUtil;
import org.apache.shindig.gadgets.servlet.HttpGadgetContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Independent mediator for corresponding OpenSocial type
 *
 * @author Jordan Zimmerman
 */
@SuppressWarnings({"deprecation"})
public class MediatedRenderingServlet extends InjectedServlet
{
	private static final int 		DEFAULT_CACHE_TTL = 60 * 5;

	private Renderer fRenderer;

	@Inject
	public void setRenderer(Renderer renderer)
	{
		this.fRenderer = renderer;
	}

	private void render(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		if (req.getHeader(HttpRequest.DOS_PREVENTION_HEADER) != null) {
		  // Refuse to render for any request that came from us.
		  // TODO: Is this necessary for any other type of request? Rendering seems to be the only one
		  // that can potentially result in an infinite loop.
		  resp.sendError(HttpServletResponse.SC_FORBIDDEN);
		  return;
		}

		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");

		GadgetContextMediator	mediatedContext = null;
		int						cacheTTL = 0;
		try
		{
			GadgetContextHandlerMediator contextHandlerMediator = MediatedDriverFactory.getDriver().getGadgetContextHandlerMediator();
			if ( contextHandlerMediator != null )
			{
				mediatedContext = contextHandlerMediator.getGadgetContextFromRequest(req);
				cacheTTL = contextHandlerMediator.getCacheTTLMinutes();
			}
		}
		catch ( Exception e )
		{
			throw new IOException(e);
		}
		GadgetContext 			context = (mediatedContext != null) ? GadgetContextMediatorFactory.i.make(mediatedContext) : new HttpGadgetContext(req);
		RenderingResults 		results = fRenderer.render(context);
		switch ( results.getStatus() )
		{
			case OK:
			{
				if ( context.getIgnoreCache() )
				{
					HttpUtil.setCachingHeaders(resp, 0);
				}
				else
				{
					HttpUtil.setCachingHeaders(resp, (cacheTTL != 0) ? cacheTTL : DEFAULT_CACHE_TTL, true);
				}

				resp.getWriter().print(results.getContent());
				break;
			}

			case ERROR:
			{
				resp.getWriter().print(results.getErrorMessage());
				break;
			}

			case MUST_REDIRECT:
			{
				resp.sendRedirect(results.getRedirect().toString());
				break;
			}
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		// If an If-Modified-Since header is ever provided, we always say
		// not modified. This is because when there actually is a change,
		// cache busting should occur.
		if ( req.getHeader("If-Modified-Since") != null && !"1".equals(req.getParameter("nocache")) && req.getParameter("v") != null )
		{
			resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		render(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		render(req, resp);
	}
}